﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Eshouse.Bll;
using Eshouse.Entity;
using System.Text;
using System.Data;
namespace Eshouse.Web.Controllers
{
    /// <summary>
    /// 笑看劳燕分飞去， 
    /// 总似台前戏中戏。
    /// 某非爱恨谁怕谁，
    /// 总有鸳鸯肯相随。
    /// </summary>
    public class AdminController : Controller
    {
        #region  管理系统用户

        /// <summary>
        /// 春日和风吹雪化，百盛桃花映春来，愉悦短暂离狮山，未知何日会相逢？
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminLoginAuth]
        public ActionResult UpdateSysUser()        
        {  
            string res = "1";
            string id = Request["Id"].ToString();
            string pwd = Request["oldpwd"].ToString();
            string newPwd = Request["userpwd"].ToString();
            string ddlrole = Request["role"].ToString();
            string state = Request["state"].ToString();
            SysRole role=new SysRole();
            role.Id=Convert.ToInt32(ddlrole);
            personAccess pa = new personAccess();
            PersonInfo pi = pa.GetUserById(Convert.ToInt32(id));
            if (newPwd != "")
            {
                if (!personAccess.VerifyUserPwd(pwd, Convert.ToInt32(id)))
                {
                    res = "旧密码不正确！";
                }
                else {                   
                    pi.PSPassword = publicComm.toMD5(newPwd);
                    pi.Role = role;
                    pi.PSState = state == "0" ? false : true;
                    pa.UpdateUser(pi);
                }                
            }
            else {
                pi.Role = role;
                pi.PSState = state == "0" ? false : true;
                pa.UpdateUser(pi);                
            }
            return Content(res);        
        }
        [AdminLoginAuth]
        public ActionResult UpdateSysUser(int? id)
        {
            personAccess pa=new personAccess();
            PersonInfo p = pa.GetUserById(Convert.ToInt32(id));
            if (p == null)
                return Content("读取数据失败，请您稍后再试");
            ViewData["username"] = p.PSUserName;
            ViewData["id"] =id;
            DataTable dt = RoleAccess.GetRoleDataTabel();
            List<SelectListItem> items = new List<SelectListItem>();
            if (dt == null)
            {
                items.Add(new SelectListItem { Text = "读取角色失败", Value = "" });
            }
            else
            {
                string role = p.Role.RoleName;
                string rolename;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    rolename = dt.Rows[i]["rolename"].ToString();
                    if (rolename == role)
                        items.Add(new SelectListItem { Text = dt.Rows[i]["rolename"].ToString(), Value = dt.Rows[i]["roleid"].ToString(), Selected = true });
                    //if (rolename == "超级管理员")
                    items.Add(new SelectListItem { Text = dt.Rows[i]["rolename"].ToString(), Value = dt.Rows[i]["roleid"].ToString() });
                }
            }
            string radioYes = "<input type='radio' name='states' id='states_yes' {0}  /> ";
            string radioNo = "<input type='radio' name='states' id='states_no' {0}  /> ";

            if (p.PSState == true)
            {
                radioYes = string.Format(radioYes, "checked='checked'");
                radioNo = string.Format(radioNo, "");
            }
            else
            {
                radioYes = string.Format(radioYes, "");
                radioNo = string.Format(radioNo, "checked='checked'");
            }
            ViewData["chk1"] = radioYes;
            ViewData["chk2"] = radioNo;
            ViewData["ddlrole"] = items;
            return View();            
        }
        [HttpPost]
        [SysAdminAuth]
        public ActionResult ResetPwd()
        {
            string res = "发生未知意外，重置失败，请您稍后再试。";
            string userid = Request["id"].ToString();
            if(personAccess.ResetPwd(userid))
            {
                res = "1";
            }           
            return Content(res);
        }
        [HttpPost]
        [SysAdminAuth]
        public ActionResult DeleteSysUser()
        {           
            string res = "1";
            int id =Convert.ToInt32(Request["id"]);
            personAccess pa = new personAccess();
            PersonInfo pi = pa.GetUserById(id);
            if(!pa.DeleteUser(pi))
            {
                res = "发生未知异常，删除失败！请您稍后再试！";
            }           
            return Content(res);
        }

        [HttpPost]
        [AdminLoginAuth]
        public ActionResult GetSysUser()
        {
           int pageidx=Convert.ToInt32(Request["page"]);
            int size = Convert.ToInt32(Request["rows"]);
            personAccess pa = new personAccess();
            return Content(pa.GetJsonDT(pageidx, size));
        }
        [HttpPost]
        public ActionResult VerifySysUserName()
        {
            string userName = Request["userName"].ToString().Trim();
            string res = "1";
            if (personAccess.VerifyUserName(userName))
            {
                res = "0";
            }
            return Content(res);
        }
        [HttpPost]
        [SysAdminAuth]
        public ActionResult InsertUser()
        {
            string username = Request["username"].ToString().Trim();
            string userpwd = Request["userpwd"].ToString().Trim();
            string roleid = Request["ddlrole"].ToString().Trim();
            string ip = Request.UserHostAddress;
            StringBuilder sbres=new StringBuilder();
            personAccess pa = new personAccess();            
            string res = "1";
            if (userpwd == "")
            {
                res = "密码不能为空!";
                return Content(res);
            }
            else {
                PersonInfo pi = new PersonInfo();
                SysRole role = new SysRole();
                role.Id =Convert.ToInt32(roleid);
                pi.PSUserName = username;
                pi.PSPassword = publicComm.toMD5(userpwd);
                pi.Role = role;
                pi.PSState = true;
                if (!pa.VerifyUserMsg(pi, ref sbres, 0))
                {
                    res = sbres.ToString();
                }
                else {
                    if (!pa.InsertNewUser(pi,ip))
                    {
                        res = "发生未知异常，注册失败！请您稍后再试！";
                    }
                }
            
            }           
            return Content(res) ;
        }
        [SysAdminAuth]
        public ActionResult AddSysUser()
        {
            List<SelectListItem> items = new List<SelectListItem>();
            DataTable dt = RoleAccess.GetRoleDataTabel();
            if (dt == null)
            {
                items.Add(new SelectListItem { Text = "读取角色失败", Value = ""});
            }
            else {
                items.Add(new SelectListItem { Text = "请选择", Value = "", Selected = true });
                for (int i = 0; i <dt.Rows.Count; i++)
                {
                    items.Add(new SelectListItem { Text = dt.Rows[i]["rolename"].ToString(), Value = dt.Rows[i]["roleid"].ToString()});
                }            
            }            
            ViewData["ddlrole"] = items;
            return View();
        }
        #endregion
        
        #region    系统角色
        [SysAdminAuth]
        public ActionResult AddRole()
        {
            return View();
        }
       
        [HttpPost]
        [SysAdminAuth]
        public ActionResult ChangeAuthor(string id)
        {
            string res = "";
            switch (id)
            {
                case "SaveRole":
                    string items = Request["item"].ToString();
                    string role = Request["role"].ToString();
                    res = RoleAccess.SaveRoleItem(items, role);
                    break;
                case "LoadRoleTree":
                    string roleName = Session["rolename"] == null ? "" : Session["rolename"].ToString();
                    res = RoleAccess.LoadRoleTree(roleName);
                    break;
            }
            return Content(res);
        }
        [SysAdminAuth]
        public ActionResult ChangeAuthor(int? id)
        {

            string rolename = RoleAccess.GetRoleNameByID(id == null ? "000000000" : id.ToString());
            ViewData["rolename"] = rolename;
            ViewData["roleTree"] = RoleAccess.LoadRoleTree(rolename);
            Session["rolename"] = rolename;
            return View();
        }
        [HttpPost]
        [SysAdminAuth]
        public ActionResult DelteRole()
        {
            string res = "1";
            string roleID = string.IsNullOrEmpty(Request["id"].ToString()) ? "1111" : Request["id"].ToString();
            if (roleID != "1111111111")
            {
                if (!RoleAccess.DeleteRole(roleID.Trim()))
                    res = "发生未知异常，删除失败，请您稍后再试！";
            }
            else
            {
                res = "超级管理员为系统内置管理员！不能删除！";
            }
            return Content(res);
        }
        [HttpPost]
        [SysAdminAuth]
        public ActionResult AddRolePost()
        {
            string res = "1";
            string roleName = string.IsNullOrEmpty(Request["roleName"].ToString()) ? "" : Request["roleName"].ToString();
            if (roleName != "")
            {
                if (!RoleAccess.VerifyRoleName(roleName.Trim()))
                {
                    if (!RoleAccess.InsertRole(roleName.Trim()))
                        res = "发生未知异常，条件失败！请您稍后再试，或者联系管理员，查看系统的日志。";
                }
            }
            else
            {
                res = "角色名称不能为空！";
            }
            return Content(res);
        }
        [HttpPost]
        public ActionResult VerifyRoleName()
        {
            string roleName = string.IsNullOrEmpty(Request["roleName"].ToString()) ? "" : Request["roleName"].ToString();
            string isExist = "1";
            if (RoleAccess.VerifyRoleName(roleName.Trim()))
                isExist = "0";
            return Content(isExist);
        }
        [HttpPost]
        [SysAdminAuth]
        public ActionResult GetRoles()
        {

            return Content(RoleAccess.GetRoleJson());
        }
        #endregion
        [HttpPost]
        [AdminLoginAuth]
        public ActionResult CreateMenu(int? id)
        {
            int pid = 0;
            try
            {
                pid = Convert.ToInt32(id);
            }
            catch { }
            return Content(MenuAccess.GetMenuOnJson(pid));
        }

        //
        // GET: /Admin/
        [AdminLoginAuth]
        public ActionResult Defualt()
        {
            return View();
        }
        [AdminLoginAuth]
        public ActionResult Index()
        {
            return View();
        }
        
        public ActionResult Login(int? id)
        {
           string code= publicComm.GetCode;
           Session["code"] = code;
           string path=Request.ApplicationPath+publicComm.GetImge(code);
           ViewData["imgpage"] = path;
            return View();
        }
        [HttpPost]
        public ActionResult Login()
        {
            string res = "1";
            string username = Request["username"];
            string passwd=Request["pwd"];
            string imgcode=Request["code"];
            if (Session["code"] == null)
            {
                res = "认证码错误！";
            }
            else {
                if (((string)Session["code"]).ToLower() == imgcode.ToLower())
                {
                    if (!personAccess.Login(username, passwd))
                    {
                        res = "请输入正确的用户名和密码！";
                    }
                    else {
                        System.Web.Security.FormsAuthentication.SetAuthCookie(username, false);                     
                    
                    }
                }
                else {
                    res = "认证码错误！";
                }
            }
            return Content(res);            
        }
        [HttpPost]
        public ActionResult GetImgCode()
        {
            string code = publicComm.GetCode;
            Session["code"] = code;
            string path = Request.ApplicationPath + publicComm.GetImge(code);
            return Content(path);
        }
        #region  类型管理，字典管理
        [AdminLoginAuth]
        public ActionResult AllCatagory()
        {
            return View();
        }
        [HttpPost]
        [AdminLoginAuth]
        public ActionResult GetCatagorys()
        {
            catagoryAccess ca = new catagoryAccess();
            int pageIdx = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);
            int pageSize = Request["rows"] == null ? 20 : Convert.ToInt32(Request["rows"]);
            return Content(ca.GetListOnJson(pageIdx, pageSize));
        }
        //删除一个类型
        [AdminLoginAuth]
        public ActionResult DelteCatagory()
        {
            int id = string.IsNullOrEmpty(Request["id"].ToString()) ? 1 : Convert.ToInt32(Request["id"]);
            catagoryAccess ca = new catagoryAccess();
            DicCode dic = new DicCode();
            dic.Id = id;
            return Content(ca.Delete(dic).ToString());
        }
        [AdminLoginAuth]
        public ActionResult CatagoryMan()
        {
            List<SelectListItem> items = new List<SelectListItem>();
            DicCode dc;
            using (catagoryAccess ac = new catagoryAccess())
            {
                IList<DicCode> list = ac.GetCatagoryList();
                items.Add(new SelectListItem { Text = "请选择", Value = "", Selected = true });
                for (int i = 0; i < list.Count; i++)
                {
                    dc = list[i];
                    items.Add(new SelectListItem { Text = dc.DictName, Value = dc.Id.ToString() });
                }
            }
            ViewData["ddlCatagory"] = items;
            ViewData["verify"] = "";
            return View();
        }
        /// <summary>
        /// 添加一个新的类型
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AdminLoginAuth]
        public ActionResult AddCatagory()
        {
            string verifyMsg = "";
            string catagoryTxt = Request["catagoryTxt"].ToString();
            StringBuilder sbres = new StringBuilder();
            catagoryAccess ac = new catagoryAccess();
            DicCode dc;
            if (catagoryAccess.VerifyCatagoryNameOnServer(catagoryTxt, ref sbres))
            {
                dc = new DicCode(catagoryTxt);
                if (!ac.InsertCatagroy(dc))
                {
                    verifyMsg = "<font color='red'>发生未知意外！添加失败，请您稍后再试。</font>";
                }
            }
            else
            {
                verifyMsg = "<font color='red'>" + sbres.ToString() + "</font>";
            }
            ViewData["verify"] = verifyMsg;
            List<SelectListItem> items = new List<SelectListItem>();
            IList<DicCode> list = ac.GetCatagoryList();
            items.Add(new SelectListItem { Text = "请选择", Value = "", Selected = true });
            for (int i = 0; i < list.Count; i++)
            {
                dc = list[i];
                items.Add(new SelectListItem { Text = dc.DictName, Value = dc.Id.ToString() });
            }
            ViewData["ddlCatagory"] = items;
            return View("CatagoryMan");
        }
        [HttpPost]
        [AdminLoginAuth]
        public ActionResult GetItems()
        {
            int pageIdx = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);
            int pageSize = Request["rows"] == null ? 20 : Convert.ToInt32(Request["rows"]);
            dictItemAccess da = new dictItemAccess();
            return Content(da.GetListOnJson(pageIdx, pageSize));
        }
        [HttpPost]
        public ActionResult VerifyCatagoryName()
        {
            string verify = "true";
            if (Request["catagoryTxt"] == null)
                Response.Write("false");
            string catagory = Request["catagoryTxt"].ToString();
            if (catagoryAccess.VerifyCatagoryName(catagory))
            {
                verify = "false";
            }
            return Content(verify);
        }
        [HttpPost]
        [AdminLoginAuth]
        public ActionResult AddItem()
        {
            string insertRes = "1";
            string itemName = Request["item"].ToString();
            int catagory = Request["cat"].ToString() == "" ? 0 : Convert.ToInt32(Request["cat"]);
            DicCode dic = new DicCode();
            dic.Id = catagory;
            DicTable newitem = new DicTable(itemName, dic);
            StringBuilder sb = new StringBuilder();
            if (dictItemAccess.VerifyItems(newitem, ref sb))
            {
                dictItemAccess da = new dictItemAccess();
                if (!da.Insert(newitem))
                {
                    insertRes = "发生了未知意外，添加失败！请稍候再试。具体的失败信息请查看系统的log日志！";
                }

            }
            else
            {
                insertRes = sb.ToString();
            }
            return Content(insertRes);
        }
        [HttpPost]
        [AdminLoginAuth]
        public ActionResult DelteItem()
        {
            string delRes = "1";
            int id = Request["id"].ToString() == "" ? 0 : Convert.ToInt32(Request["id"]);
            using (dictItemAccess da = new dictItemAccess())
            {
                if (!da.Delete(id))
                {
                    delRes = "发生未知异常，删除失败！请您稍后再试，或者联系管理员，或者您可以查看系统的log日志！";
                }
            }
            return Content(delRes);
        }
        [HttpPost]
        [AdminLoginAuth]
        public ActionResult LoadHtmlTable_Edit()
        {
            string id = Request["id"].ToString();
            return Content(dictItemAccess.GetMsgOnHtmlTb_Edit(id));
        }
        [HttpPost]
        [AdminLoginAuth]
        public ActionResult EnsureUpdate()
        {
            string res = "1";
            string id = Request["id"];
            string catagory = Request["catagory"];
            string itemName = Request["itemName"];
            DicTable dic = new DicTable();
            DicCode dicc = new DicCode();
            dicc.Id = Convert.ToInt32(catagory);
            dic.Id = Convert.ToInt32(id);
            dic.ItemName = itemName;
            dic.dictid = dicc;
            StringBuilder sb = new StringBuilder();
            if (dictItemAccess.VerifyItems(dic, ref sb))
            {
                using (dictItemAccess da = new dictItemAccess())
                {
                    if (!da.Update(dic))
                    {
                        res = "发生未知意外！更新失败！请您稍后再试！或者联系管理员！";
                    }
                }
            }
            else
            {
                res = sb.ToString();
            }
            return Content(res);
        }
        #endregion
    }
}
